package com.juli.aimanager.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;

public class CheckCRC {
	/**
	 * 获取文件的CRC
	 * @param filepath
	 * @return
	 * @throws IOException
	 */
	public static long checksumBufferedInputStream(String filepath)
			throws IOException {
		InputStream inputStream = new BufferedInputStream(new FileInputStream(
				filepath));
		CRC32 crc = new CRC32();
		int cnt;
		while ((cnt = inputStream.read()) != -1) {
			crc.update(cnt);
		}
		return crc.getValue();
	}
	/**
	 * 第二种方式生成CRC
	 * @param filePath 文件路径
	 * @return
	 */
	public static String getFileCRCValue(String filePath) {
		File updateFile = new File(filePath);
		if (!updateFile.exists()) {
		}
		CRC32 crc32 = new CRC32();
		FileInputStream inputStream = null;
		CheckedInputStream checkedinputstream = null;
		String crcStr = null;
		try {
			inputStream = new FileInputStream(new File(filePath));
			checkedinputstream = new CheckedInputStream(inputStream, crc32);
			while (checkedinputstream.read() != -1) {
			}
			crcStr = Long.toHexString(crc32.getValue()).toUpperCase();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			}
			if (checkedinputstream != null) {
				try {
					checkedinputstream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return crcStr;
	}
	public static void main(String[] args) throws IOException {
		String filePath = "G:/1.txt";
		System.out.println(getFileCRCValue("G:/test.apk"));
	}
}
